
<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { editUserPassword } from '@/api/user.js'

const pwdFormRef = ref(null)
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// 表单校验规则
const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度需在6到15位之间', trigger: 'blur' },
    { validator: validateOldNewPassword, trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度需在6到15位之间', trigger: 'blur' },
    { validator: validateOldNewPassword, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度需在6到15位之间', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 校验：原密码和新密码不能一样
function validateOldNewPassword(rule, value, callback) {
  if (pwdForm.value.old_pwd && pwdForm.value.old_pwd === pwdForm.value.new_pwd) {
    callback(new Error('原密码和新密码不能相同'))
  } else {
    callback()
  }
}

// 校验：新密码和确认密码必须一致
function validateConfirmPassword(rule, value, callback) {
  if (pwdForm.value.new_pwd && pwdForm.value.new_pwd !== pwdForm.value.re_pwd) {
    callback(new Error('新密码和确认密码不一致'))
  } else {
    callback()
  }
}

// 提交表单
const submitForm = () => {
  pwdFormRef.value.validate(async (valid) => {
    if (valid) {
      // 可以在这里添加密码更新的请求逻辑
      await editUserPassword(pwdForm.value)
      ElMessage.success('密码修改成功')

    } else {
      ElMessage.error('请检查输入内容')
    }
  })
}

// 重置表单
const resetForm = () => {
  pwdFormRef.value.resetFields()
}
</script>

<template>
  <el-form
    ref="pwdFormRef"
    :model="pwdForm"
    :rules="rules"
    label-width="100px"
    class="password-form"
  >
    <!-- 原密码 -->
    <el-form-item label="原密码" prop="old_pwd">
      <el-input v-model="pwdForm.old_pwd" type="password" placeholder="请输入原密码" />
    </el-form-item>

    <!-- 新密码 -->
    <el-form-item label="新密码" prop="new_pwd">
      <el-input v-model="pwdForm.new_pwd" type="password" placeholder="请输入新密码" />
    </el-form-item>

    <!-- 确认密码 -->
    <el-form-item label="确认密码" prop="re_pwd">
      <el-input v-model="pwdForm.re_pwd" type="password" placeholder="请确认新密码" />
    </el-form-item>

    <!-- 操作按钮 -->
    <el-form-item>
      <el-button type="primary" @click="submitForm">修改密码</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>


<style scoped>
.password-form {
  max-width: 400px;
  margin: 0 auto;
}
</style>
